package com.example.zbh.dsliao.ui.activty;

import android.content.Context;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMCallStateChangeListener;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EMNetworkUnconnectedException;
import com.easemob.exceptions.EMNoActiveCallException;
import com.easemob.exceptions.EMServiceNotReadyException;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;

import java.util.UUID;

/**
 * Created by zbh on 15/11/28.
 */
public class VoiceCallActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout ll_coming_call, ll_voice_control, root_layout;

    private Button btn_hangup_call, btn_answer_call, btn_refuse_call;
    private ImageView iv_mute, iv_handsfree;
    private TextView tv_call_state, tv_nick, tv_calling_duration, tv_is_p2p;
    private Chronometer chronometer;
    private EMCallStateChangeListener callStateListener;//电话监听
    private int streamId;
    private Handler handler;

    private boolean isInComingCall;//判断是否进来电话
    private boolean isAnswer;
    private boolean endCallTriggerByme = false;
    private boolean isHandsfreeState;
    private boolean isMuteState;
    private String userName;//联系人
    private CallingState callingState = CallingState.CANCED;
    private String callDruationText;
    private String msgId;
    private AudioManager audioManager;
    private SoundPool soundPool;
    private Ringtone ringtone;
    private int outGoing;


    @Override
    protected int getLayOut() {
        return R.layout.activity_voice_call;
    }

    @Override
    protected void initView() {
        ll_coming_call = findeView(R.id.ll_coming_call);
        ll_voice_control = findeView(R.id.ll_voice_control);
        btn_hangup_call = findeView(R.id.btn_hangup_call);
        btn_answer_call = findeView(R.id.btn_answer_call);
        btn_refuse_call = findeView(R.id.btn_refuse_call);
        tv_is_p2p = findeView(R.id.tv_is_p2p);
        iv_mute = findeView(R.id.iv_mute);
        iv_handsfree = findeView(R.id.iv_handsfree);
        tv_call_state = findeView(R.id.tv_call_state);
        tv_nick = findeView(R.id.tv_nick);
        tv_calling_duration = findeView(R.id.tv_calling_duration);
        chronometer = findeView(R.id.chronometer);
        root_layout = findeView(R.id.root_layout);
    }

    @Override
    protected void initData() {
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        handler = new Handler();
        btn_hangup_call.setOnClickListener(this);
        btn_answer_call.setOnClickListener(this);
        btn_refuse_call.setOnClickListener(this);
        iv_handsfree.setOnClickListener(this);
        iv_mute.setOnClickListener(this);

        // 注册语音电话的状态的监听
        addCallStateListener();
        msgId = UUID.randomUUID().toString();
        userName = getIntent().getStringExtra("username");
        //语音电话是否为接收的
        isInComingCall = getIntent().getBooleanExtra("isComingCall", false);
        //设置通话联系人
        tv_nick.setText(userName);
        if (!isInComingCall) {//拨打电话
            soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
            outGoing = soundPool.load(this, R.raw.em_outgoing, 1);
            ll_coming_call.setVisibility(View.VISIBLE);
            btn_hangup_call.setVisibility(View.VISIBLE);
            tv_call_state.setText("正在连接对方");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    streamId = playMakeCallSounds();
                }
            }, 400);
            try {
                EMChatManager.getInstance().makeVoiceCall(userName);
            } catch (EMServiceNotReadyException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(VoiceCallActivity.this, "尚未连接到服务器", Toast.LENGTH_SHORT).show();
                    }
                });
            }


        } else {//有电话进来
            ll_voice_control.setVisibility(View.VISIBLE);
            Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            audioManager.setMode(AudioManager.MODE_RINGTONE);
            audioManager.setSpeakerphoneOn(true);
            ringtone = RingtoneManager.getRingtone(this, ringUri);
            ringtone.play();
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_hangup_call://挂断
                hangUpCalling();
                break;
            case R.id.btn_answer_call://接听
                answerCalling();
                break;
            case R.id.btn_refuse_call://拒绝接听
                refuseCalling();
                break;
            case R.id.iv_handsfree://免提
                clickHandFree();
                break;
            case R.id.iv_mute://静音
                ClickMute();

                break;
        }
    }


    //注册电话监听
    private void addCallStateListener() {
        callStateListener = new EMCallStateChangeListener() {
            @Override
            public void onCallStateChanged(CallState callState, CallError callError) {
                switch (callState) {
                    case CONNECTING://正在连接对方
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_call_state.setText("正在连接对方...");
                            }
                        });
                        break;
                    case CONNECTED://双方已经建立连接
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_call_state.setText("已和对方建立连接,正在等待对方接受...");
                            }
                        });
                        break;
                    case ACCEPTED://电话接通成功
                        sucCalling();
                        break;
                    case DISCONNNECTED:
                        disConnectedCalling(callError);
                }

            }
        };
        EMChatManager.getInstance().addCallStateChangeListener(callStateListener);
    }


    enum CallingState {
        CANCED, NORMAL, REFUESD, BEREFUESD, UNANSWERED, OFFLINE, NORESPONSE, BUSY
    }
    //电话断了
    private void disConnectedCalling(final EMCallStateChangeListener.CallError callError) {
        runOnUiThread(new Runnable() {
            private void postDelayedCloseMsg(){
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        saveCallRecord();
                        Animation animation = new AlphaAnimation(1.0f, 0.0f);
                        animation.setDuration(800);
                        root_layout.startAnimation(animation);
                        finish();

                    }
                }, 200);
            }
            @Override
            public void run() {
                chronometer.stop();
                callDruationText = chronometer.getText().toString();
                if (callError == EMCallStateChangeListener.CallError.REJECTED){
                    callingState = CallingState.BEREFUESD;
                    tv_call_state.setText("对方拒绝接受");
                }else if (callError == EMCallStateChangeListener.CallError.ERROR_TRANSPORT){
                   tv_call_state.setText("连接建立失败");
                }else if (callError == EMCallStateChangeListener.CallError.ERROR_INAVAILABLE) {
                    callingState = CallingState.OFFLINE;
                    tv_call_state.setText("对方不在线,请稍后再拨");
                }else if (callError == EMCallStateChangeListener.CallError.ERROR_BUSY){
                    callingState = CallingState.BUSY;
                    tv_call_state.setText("对方正在通话中,请稍后再拨");
                }else if (callError == EMCallStateChangeListener.CallError.ERROR_NORESPONSE){
                    callingState = CallingState.NORESPONSE;
                    tv_call_state.setText("对方未接听");
                }else {
                    if (isAnswer){
                        callingState = CallingState.NORMAL;
                        if (endCallTriggerByme){
                            tv_call_state.setText("挂断");
                        }else {
                            tv_call_state.setText("对方已取消");
                        }
                    }else {
                        if (isInComingCall){
                            callingState = CallingState.UNANSWERED;
                            tv_call_state.setText("未接听");
                        }else {
                            if (callingState != CallingState.NORMAL){
                                callingState = CallingState.CANCED;
                                tv_call_state.setText("已取消");
                            }else {
                                tv_call_state.setText("挂断");
                            }
                        }
                    }
                }
                postDelayedCloseMsg();

            }
        });

    }


    //电话接听成功
    private void sucCalling() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (soundPool != null) {
                        soundPool.stop(streamId);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        if (!isHandsfreeState){
            closeSpeakerOn();
        }
        tv_is_p2p.setText(EMChatManager.getInstance().isDirectCall() ? "直播" : "重播");
        chronometer.setVisibility(View.VISIBLE);
        chronometer.setBase(SystemClock.elapsedRealtime());
        //开始计时
        chronometer.start();
        tv_call_state.setText("通话中....");
        callingState = CallingState.NORMAL;




    }


    //静音
    private void ClickMute() {
        if (isMuteState){//关闭静音
            iv_mute.setImageResource(R.mipmap.dl_icon_mute_normal);
            audioManager.setMicrophoneMute(false);
            isMuteState = false;
        }else {//打开静音
            iv_mute.setImageResource(R.mipmap.dl_icon_mute_on);
            audioManager.setMicrophoneMute(true);
            isMuteState = true;
        }


    }


    //免提
    private void clickHandFree() {
        if (isHandsfreeState) {//关闭免提
            iv_handsfree.setImageResource(R.mipmap.dl_icon_speaker_normal);
            closeSpeakerOn();
            isHandsfreeState = false;
        } else {
            iv_handsfree.setImageResource(R.mipmap.dl_icon_speaker_on);
            openSpeakerOn();
            isHandsfreeState = true;
        }


    }

    //拒绝接听电话
    public void refuseCalling() {
        btn_refuse_call.setEnabled(false);
        if (ringtone != null) {
            ringtone.stop();
        }
        try {
            EMChatManager.getInstance().rejectCall();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
            saveCallRecord();
            finish();
        }
        callingState = CallingState.REFUESD;
    }

    //挂断电话
    private void hangUpCalling() {
        btn_hangup_call.setEnabled(false);
        if (soundPool != null) {
            soundPool.stop(streamId);
        }
        chronometer.stop();
        endCallTriggerByme = true;
        tv_call_state.setText("正在挂断...");
        try {
            EMChatManager.getInstance().endCall();
        } catch (Exception e) {
            e.printStackTrace();
            saveCallRecord();
            finish();
        }

    }

    //接听电话
    private void answerCalling() {
        btn_answer_call.setEnabled(false);
        if (ringtone != null) {
            ringtone.stop();
        }
        if (isInComingCall) {

            try {
                tv_call_state.setText("正在接听");
                EMChatManager.getInstance().answerCall();
                isAnswer = true;
            } catch (EMNoActiveCallException e) {
                e.printStackTrace();
                saveCallRecord();
                finish();
                return;
            } catch (EMNetworkUnconnectedException e) {
                e.printStackTrace();
                saveCallRecord();
                finish();
                return;
            }
            ll_coming_call.setVisibility(View.INVISIBLE);
            btn_hangup_call.setVisibility(View.VISIBLE);
            ll_voice_control.setVisibility(View.VISIBLE);
            closeSpeakerOn();
        }
    }


    //播放拨号响铃
    private int playMakeCallSounds() {
        try {

            //最大音量
            float audioMaxVolumn = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
            //当前音量
            float audioCurrentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_RING);
            audioManager.setMode(AudioManager.MODE_RINGTONE);
            audioManager.setSpeakerphoneOn(false);
            int id = soundPool.play(outGoing,//声音资源
                    0.3f,//左声道
                    0.3f,//右声道
                    1,//优先级
                    -1,//循环次数,0是不循环,-1是永远循环
                    1//回放速度0.5-2.0之间.1为正常速度
            );
            return id;
        } catch (Exception e) {
            return -1;
        }
    }

    //打开扬声器
    private void openSpeakerOn() {
        try {
            if (!audioManager.isSpeakerphoneOn())
                audioManager.setSpeakerphoneOn(true);
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭扬声器
    private void closeSpeakerOn() {
        try {
            if (audioManager != null)
                audioManager.setSpeakerphoneOn(false);
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //保存通话记录
    private void saveCallRecord() {
        EMMessage message = null;
        TextMessageBody textBody = null;
        if (!isInComingCall) {
            message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            message.setReceipt(userName);
        } else {
            message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            message.setFrom(userName);
        }
        switch (callingState) {
            case NORMAL:
                textBody = new TextMessageBody("通话时长" + callDruationText);
                break;
            case REFUESD:
                textBody = new TextMessageBody("已拒绝");
                break;
            case BEREFUESD:
                textBody = new TextMessageBody("对方已拒绝");
                break;
            case OFFLINE:
                textBody = new TextMessageBody("对方不在线");
                break;
            case BUSY:
                textBody = new TextMessageBody("对方正在通话中");
                break;
            case NORESPONSE:
                textBody = new TextMessageBody("对方未接听");
                break;
            case UNANSWERED:
                textBody = new TextMessageBody("未接听");
                break;
            default:
                textBody = new TextMessageBody("已取消");
                break;
        }
        message.setAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, true);
        message.addBody(textBody);
        message.setMsgId(msgId);
        EMChatManager.getInstance().saveMessage(message, false);


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        EMChatManager.getInstance().endCall();
        callDruationText = chronometer.getText().toString();
        saveCallRecord();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (soundPool != null) {
            soundPool.release();
        }
        if (ringtone != null && ringtone.isPlaying()) {
            ringtone.stop();
        }
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setMicrophoneMute(false);
        if (callStateListener != null) {
            EMChatManager.getInstance().removeCallStateChangeListener(callStateListener);
        }
    }

}
